import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import Tkinter as Tk
from tkMessageBox import showinfo
import subprocess
import tkFileDialog
import sys
from Tkinter import *
import tkFileDialog
import numpy
import math
import time
import thread

def receive_thread(popen,id):
    while True:             
        next_line = popen.stdout.readline()
        v1.set(next_line.strip())
    thread.exit_thread()

def stop():
    popen.stdin.write("END" +'\n')

def send():
    popen.stdin.write(v2.get() +'\n')
    v2.set('')

def clear():
    v1.set('')
    v2.set('')

class FlushFile(object): 
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()
        
def Execute_File():
    global popen
    sys.stdout = FlushFile(sys.__stdout__)
    popen = subprocess.Popen(['./tcp_server.sh'], stdin=subprocess.PIPE,stdout = subprocess.PIPE)

def start():
    v1.set('waiting for clients')
    Execute_File()
    thread.start_new_thread(receive_thread, (popen,1)) 

"""
build GUI
"""
windows=Tk() #create windows
label0 = Label(windows,text='Server') #create project title
label0.pack()
    
f0=Frame(windows) # display received msg
f0.pack()
label1=Label(f0,text='Read')
label1.pack(side=LEFT)
v1 = StringVar()
Input1= Entry(f0, textvariable=v1,width=40,justify=LEFT)
Input1.pack(side=LEFT)
v1.set('')
    
f3=Frame(windows) # write msg to be sent
f3.pack()
label4 = Label(f3,text='Write')
label4.pack(side=LEFT)
v2 = StringVar()
Input5= Entry(f3, textvariable=v2,width=40,justify=LEFT)
Input5.pack(side=LEFT)
v2.set('')

f1 = Frame(windows) # button of send and clear
f1.pack()
but0=Button(f1, text='Start')
but0.pack(side=LEFT)
but1=Button(f1, text='Stop')
but1.pack(side=LEFT)
but2=Button(f1, text='Send')
but2.pack(side=LEFT)
but3=Button(f1, text='Clear')
but3.pack(side=LEFT)
but0.configure(command=start)
but1.configure(command=stop)
but2.configure(command=send)
but3.configure(command=clear)
windows.mainloop()


